# -*- coding: utf-8 -*-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者：cacho_37967865
#博客：https://blog.csdn.net/sinat_37967865
#文件：tensorflow_mnist_test_simple.py
#日期：2019-11-12
#备注：官方入门教程：Softmax回归模型
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

from PIL import Image
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import time

sTime = time.time()
mnist = input_data.read_data_sets('F:\PythonProject\Mnist', one_hot=True)    # MNIST数据集所在路径

def imageprepare():
    im = Image.open("F:\PythonProject\machinelearn\images\\test-0.png")  # 读取的图片所在路径，注意是28*28像素
    im = im.convert('L')
    tv = list(im.getdata())
    tva = [(255 - x) * 1.0 / 255.0 for x in tv]
    print(tva)
    return tva

# 实现回归模型
x = tf.placeholder(tf.float32, [None, 784])     # 输入任意数量的MNIST图像
W = tf.Variable(tf.zeros([784,10]))             # 权重W
b = tf.Variable(tf.zeros([10]))                 # 偏置b

y_ = tf.placeholder(tf.float32, [None, 10])     # 输入实际标签值


# 训练模型：成本函数“交叉熵”（cross-entropy）
y = tf.nn.softmax(tf.matmul(x,W) + b)           # 实现我们的模型
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
#train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)  # 用梯度下降算法（gradient descent algorithm）以0.01的学习速率最小化交叉熵
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)    # AdamOptimizer优化器

# 评估我们的模型
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))         # 模型对比实际
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# 创建 Saver() 对象，保存模型
saver = tf.train.Saver()
result = imageprepare()

# 初始化我们创建的变量
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    saver.restore(sess, 'F:\PythonProject\Mnist\model\simple\mnist.ckpt')    # 使用模型，参数和之前的代码保持一致
    prediction = tf.argmax(y, 1)
    predint = prediction.eval(feed_dict={x: [result]}, session=sess)

    print('识别结果:')
    print(predint[0])

eTime = time.time()
s = eTime - sTime
print('花费的时间为：%.2f秒' % (s))